from models import MetricSite, MetricStat
from variables import MetricVariables
from sync import sync_provider_to_db

def do_collect_metrics(site_name, metric_provider, site_check_mins=60, collection_time=None):
    
    # Creates or updates all database entries for metric sites, sets, and defns.
    # Returns the (possibly new) MetricSite for our convenience.
    site = sync_provider_to_db(metric_provider, site_name, site_check_mins)
    
    metric_vars = MetricVariables(site, collection_time)
    print "Checking site %s at %s" % (site_name, metric_vars.site_collection_time)
    
    for (set_name, set_defn) in metric_provider.sets.iteritems():
        set = site.get_set(set_name)
        # First see if it's time to check this set 
        metric_vars.fit_set(set)
        if metric_vars.next_collection_time <= metric_vars.collection_time:
            print "Collecting set %s at %s" % (set.name, metric_vars.collection_time)
            for (defn_name, defn_function) in set_defn.stats.iteritems():
                defn = set.get_defn(defn_name)
                value = defn_function(metric_provider, metric_vars)
                print "Collected %f for %s" % (value, defn_name)
                stat = MetricStat(metricdefn=defn, time_collected=metric_vars.collection_time, value=value).save()
            # Mark set as collected
            set.last_collected = metric_vars.collection_time
            if set.earliest_time_collected is None:
                set.earliest_time_collected = metric_vars.collection_time
            set.save()
        else:
            print "Skipping set %s at %s" % (set.name, metric_vars.collection_time)
            
    # Mark whole site as collected
    site.last_checked = metric_vars.site_collection_time
    site.save()

class Defn:
    def __init__(self, description, collection_mins=60, shadow_mins=0, stats={}):
        self.description = description
        self.collection_mins = collection_mins
        self.shadow_mins = shadow_mins
        self.stats = stats
